import json
import os
import time
from enum import Enum
from typing import Optional
from dotenv import load_dotenv
from fastapi import APIRouter, Depends, Body
from openai import BaseModel
from sqlalchemy.orm import Session

from ..crud.user_crud import get_user_by_name
from ..database.db import get_db
from ..models.ai_models.pictrue_api import run_coze_workflow as create_picture_ai
from ..schemas.base import ResponseModel
from ..utils.photo_tools import download_image, get_image_as_base64
from ..crud.image_crud import create_image as create_image_db, get_image_by_id, update_image
from ..utils.jwt_handler import get_username
# from models.ai_models.ocr_mix_instig import UniversalOcr,get_result
from ..utils.uploads_oss import main as upload_on_oss
from ..models.ai_models.picture.pictrue_style import run_coze_workflow as change_picture_style
from ..models.ai_models.hello_ocr import Sample
picture_router=APIRouter(prefix="/picture", tags=["图片"])

@picture_router.get("/")
async def get_picture():
    return {"message":"图片"}
class PictureCreate(BaseModel):
    text: str
    picture_name: str

@picture_router.post("/create")
async def create_picture(params: PictureCreate,db: Session = Depends(get_db),username: str = Depends(get_username)):
    """
    # 创建图片
    * text:图片描述
    * picture_name:图片名
    """
    load_dotenv()
    # 现在可以读取环境变量
    WORKFLOW_ID = os.getenv("WORKFLOW_ID_PICTURE")
    API_TOKEN = os.getenv("API_TOKEN")
    SOURCES_PATH=os.getenv("SOURCES_PATH")

    result = create_picture_ai(params. text, workflow_id=WORKFLOW_ID, api_token=API_TOKEN)
    result=result[0]

    print(result)
    try:
        video_data = json.loads(result)
        image_url = video_data.get("output")

    except json.JSONDecodeError:
        image_url = None

    img_hou_url="sources/pictures/download/"+f"{params.picture_name}.jpg"
    flage=0
    save_path = os.path.join(SOURCES_PATH, img_hou_url)
    # upload_on_oss(file_path=file_path, key=path)
    if image_url:
        download_image(image_url, save_path)
        upload_on_oss(file_path=save_path, key=img_hou_url)
        # return {"message": "Video downloaded", "path": save_path}
        flage=1
    else:
        # return {"error": "No video URL found"}
        flage=0

    picture_all_name=f"{params.picture_name}.jpg"
    image_db=create_image_db(db,picture_all_name,img_hou_url,type=1)
    print(image_db)

    if flage==1:
        return {
            "code":200,
            "message": "Picture downloaded",
            "data": {
                "image_item":image_db,
                "image_url":image_url,
                # "image_hou_url":img_hou_url,
                "image_base64":get_image_as_base64(save_path),
            }
        }
    else:
        return {
            "code": 500,  # 或者其他适当的错误码
            "message": "No Picture URL found",
            "data": None,  # 保持 data 字段存在，但设为 None
            "image": None  # 或者 ""
        }
class PictureUnderstandParams(BaseModel):
    image_id:int=...

@picture_router.post("/understand")
async def understand_picture(param: PictureUnderstandParams,db: Session = Depends(get_db),username: str = Depends(get_username)):
    """
    # 图片文字提取
    """
    image_path=get_image_by_id(db,param.image_id).get("path")
    load_dotenv()
    SOURCES_PATH = os.getenv("SOURCES_PATH")
    image_all_path=os.path.join(SOURCES_PATH, image_path)
    ocr_session=Sample()
    ocr_session.create_client()
    result1=ocr_session.main(image_all_path)
    result=json.loads(result1).get("content")

    return {
        "code":200,
        "message":"success",
        "data":{
            "result":result
        }
    }

from fastapi import UploadFile, File

class PictureUploadParams(BaseModel):
    # 可选：添加额外参数，如描述、标签等
    description: str = None


@picture_router.post("/upload")
async def upload_picture(
    file: UploadFile = File(...),
    db: Session = Depends(get_db),
    username: str = Depends(get_username)
):
    """
    上传图片接口
    - file: 上传的图片文件（支持 jpg/png 等格式）
    - return: 图片存储路径及 base64 编码数据
    """

    # 1. 获取文件后缀并构造新文件名
    file_extension = os.path.splitext(file.filename)[1]
    if file_extension.lower() not in [".jpg", ".jpeg", ".png", ".gif", ".bmp"]:
        return {
            "code": 400,
            "message": "不支持的文件类型",
            "data": None
        }

    # 加载环境变量
    load_dotenv()
    SOURCES_PATH = os.getenv("SOURCES_PATH")

    # 创建上传目录（如果不存在）
    # os.makedirs(PICTURE_UPLOAD_PATH, exist_ok=True)
    # 构造唯一文件名（防止重名）
    new_filename = f"{int(time.time())}_{file.filename}"

    picture_hou_url="sources/pictures/upload/"+new_filename

    save_path=os.path.join(SOURCES_PATH, picture_hou_url)

    # 2. 保存文件到本地
    with open(save_path, "wb") as buffer:
        content = await file.read()
        buffer.write(content)

    # 3. 可选：将图片信息写入数据库
    image_db = create_image_db(db, new_filename, picture_hou_url, type=2)  # type=0 表示上传图片

    # 4. 返回响应
    return {
        "code": 200,
        "message": "图片上传成功",
        "data": {
            "picture_item":image_db,
            "picture_url": picture_hou_url,
            "base64": get_image_as_base64(save_path),  # 若有需要可返回 base64 数据

        }
    }
class PictureParams(BaseModel):
    image_url:str= ...
    image_name:str= ...

class PictureStyle(str,Enum):
    american_comics= "american_comics"
    clay= "clay"
    funny_doodles= "funny_doodles"
    meticulous="meticulous"
@picture_router.post("/style")
async def style_picture(params: PictureParams, style: PictureStyle, db: Session = Depends(get_db), username: str = Depends(get_username)):
    """
    # 图片加滤镜
    """
    image_url=params.image_url
    load_dotenv()
    API_TOKEN=os.getenv("API_TOKEN")

    WORKFLOW_ID = "7524554138333528064"  # picture_style,风格为美漫
    WORKFLOW_ID1 = "7524555233420181523"  # style3，风格为粘土
    WORKFLOW_ID2 = "7524554969475940367"  # style2，风格为搞笑涂鸦
    WORKFLOW_ID3 = "7524554698281975818"  # style1，风格为工笔画

    result=""
    if style==PictureStyle.american_comics:
        result=json.loads(change_picture_style(image_url,workflow_id=WORKFLOW_ID,api_token=API_TOKEN)).get("output")
    elif style==PictureStyle.clay:
        result=json.loads(change_picture_style(image_url,workflow_id=WORKFLOW_ID1,api_token=API_TOKEN)).get("output")
    elif style==PictureStyle.funny_doodles:
        result=json.loads(change_picture_style(image_url,workflow_id=WORKFLOW_ID2,api_token=API_TOKEN)).get("output")
    elif style==PictureStyle.meticulous:
        result=json.loads(change_picture_style(image_url,workflow_id=WORKFLOW_ID3,api_token=API_TOKEN)).get("output")

    else:
        return {
            "code": 400,
            "message": "不支持的图片风格",
            "data":{
                "image_url":None
            }
        }
    load_dotenv()
    SOURCES_PATH = os.getenv("SOURCES_PATH")

    # image_db=get_image_by_id(db,params.image_id)
    # image_db_name=image_db.get("path")
    image_hou_url="sources/pictures/download/"+f"{params.image_name}.jpg"
    save_path = os.path.join(SOURCES_PATH, image_hou_url)

    image_all_name=f"{params.image_name}.jpg"
    image_db=create_image_db(db, image_all_name, image_hou_url, type=2)

    # img_hou_style_url="sources/pictures/style/"+image_db_name


    # image_item=create_image_db(db, params.image_name, img_hou_style_url, type=2)
    download_image(save_path=save_path,url=result)
    upload_on_oss(key=image_hou_url,file_path=save_path)
    return{
        "code": 200,
        "message": "图片风格转换成功",
        "data":{
            "image_url":result,
            "image_item":image_db
        }
    }

@picture_router.post("/montage-update",response_model=ResponseModel)
async def update_montage(id:int=Body(...),
                         file:UploadFile=File(...,description="图片"),
                         db: Session = Depends(get_db),
                         username: str = Depends(get_username)):
    """
    # 剪辑后保存
    - id 图片id
    """
    user=get_user_by_name(db,username)
    image_db=get_image_by_id(db,id).get("path")

    load_dotenv()
    SOURCES_PATH = os.getenv("SOURCES_PATH")
    img_path=os.path.join(SOURCES_PATH,image_db)

    # 写入新文件（覆盖原图）
    with open(img_path, "wb") as buffer:
        content = await file.read()
        buffer.write(content)
    return {
        "code": 200,
        "message": "图片保存成功",
        "data":{
            "image_url":image_db
        }
    }
class ImageUpdateParams(BaseModel):
    image_id:int=...
    image_name:str= ...
@picture_router.post("/update",response_model=ResponseModel)
async def update_picture(params: ImageUpdateParams,
                         db: Session = Depends(get_db),
                         username: str = Depends(get_username)):
    """
    # 修改图片
    - id 图片id
    """
    user=get_user_by_name(db,username)

    image_id=params.image_id
    image_name=params.image_name

    image_all_name=f"{image_name}.jpg"
    image_db=update_image(db,image_id,{"name":image_all_name})
    return {
        "code": 200,
        "message": "图片修改成功",
        "data":{
            "image_item":image_db
        }
    }